<template>
  <div class="container">
    <el-card class="fullscreen-card">
      <el-tabs v-model="tabActiveName" class="demo-tabs">
        <el-tab-pane v-loading="loading" label="审批信息" name="info">
          <div>
            <el-table :data="historyList" style="width: 100%" border fit>
              <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
              <el-table-column prop="nodeName" label="任务名称" sortable align="center"></el-table-column>
              <el-table-column prop="approveName" :show-overflow-tooltip="true" label="办理人" sortable align="center">
                <template #default="scope">
                  <template v-if="scope.row.approveName">
                    <el-tag v-for="(item, index) in scope.row.approveName.split(',')" :key="index" type="success">{{ item }}</el-tag>
                  </template>
                  <template v-else> <el-tag type="success">无</el-tag></template>
                </template>
              </el-table-column>
              <el-table-column prop="flowStatus" label="状态" width="80" sortable align="center">
                <template #default="scope">
                  <dict-tag :options="wf_task_status" :value="scope.row.flowStatus"></dict-tag>
                </template>
              </el-table-column>
              <el-table-column prop="message" label="审批意见" :show-overflow-tooltip="true" sortable align="center"></el-table-column>
              <el-table-column prop="updateTime" label="办理时间" width="160" :show-overflow-tooltip="true" sortable align="center"></el-table-column>
              <el-table-column prop="attachmentList" width="120" label="附件" align="center">
                <template #default="scope">
                  <el-popover v-if="scope.row.attachmentList && scope.row.attachmentList.length > 0" placement="right" :width="310" trigger="click">
                    <template #reference>
                      <el-button type="primary" style="margin-right: 16px">附件</el-button>
                    </template>
                    <el-table border :data="scope.row.attachmentList">
                      <el-table-column prop="originalName" width="202" :show-overflow-tooltip="true" label="附件名称"></el-table-column>
                      <el-table-column prop="name" width="80" align="center" :show-overflow-tooltip="true" label="操作">
                        <template #default="tool">
                          <el-button type="text" @click="handleDownload(tool.row.ossId, tool.row.originalName)">下载</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane v-loading="loading" label="流程图" name="image" style="height: 68vh">
          <flowChart :ins-id="insId" v-if="insId" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script setup lang="ts">
// a.js
import './a.js';
import { flowHisTaskList } from '@/api/workflow/instance';
import { propTypes } from '@/utils/propTypes';
import { listByIds } from '@/api/system/oss';
import FlowChart from '@/components/Process/flowChart.vue';
import { setToken } from '@/utils/auth';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wf_task_status } = toRefs<any>(proxy?.useDict('wf_task_status'));
const loading = ref(false);
const historyList = ref<Array<any>>([]);
const tabActiveName = ref('image');
const insId = ref(null);

const handleDownload = (ossId: string, originalName: string) => {
  // if (window.parent && window.parent !== window) {
  //   window.parent.postMessage(
  //     {
  //       type: 'download',
  //       ossId: ossId,
  //       filename: originalName
  //     },
  //     '*'
  //   );
  // }
  uni.postMessage({
    data: {
      info: {
        ossId: ossId,
        originalName: originalName
      }
    }
  });
};
//初始化查询审批记录
const init = async (businessId: string | number) => {
  loading.value = true;
  tabActiveName.value = 'info';
  historyList.value = [];
  flowHisTaskList(businessId).then((resp) => {
    if (resp.data) {
      historyList.value = resp.data.list;
      insId.value = resp.data.instanceId;
      if (historyList.value.length > 0) {
        historyList.value.forEach((item) => {
          if (item.ext) {
            getIds(item.ext).then((res) => {
              item.attachmentList = res.data;
            });
          } else {
            item.attachmentList = [];
          }
        });
      }
      loading.value = false;
    }
  });
};
const getIds = async (ids: string | number) => {
  const res = await listByIds(ids);
  return res;
};

const routeParams = ref<Record<string, any>>({});
onMounted(async () => {
  document.addEventListener('plusready', function () {
    console.log('plusready');
  });
  // 设置支持缩放的 viewport
  setupViewportForZoom();

  routeParams.value = proxy?.$route.query;
  await setToken(routeParams.value.token);
  init(routeParams.value.businessId);
});

// 设置支持缩放的 viewport
const setupViewportForZoom = () => {
  // 移除现有的 viewport meta 标签
  const existingViewports = document.querySelectorAll('meta[name="viewport"]');
  existingViewports.forEach((viewport) => viewport.remove());

  // 添加支持缩放的 viewport，适配 1200px 宽度
  const viewport = document.createElement('meta');
  viewport.name = 'viewport';
  viewport.content = 'width=1200, initial-scale=0.3, maximum-scale=3.0, minimum-scale=0.1, user-scalable=yes';
  document.head.appendChild(viewport);

  // 添加支持缩放的全局样式
  const style = document.createElement('style');
  style.textContent = `
    * {
      touch-action: manipulation !important;
    }
    html, body {
      touch-action: manipulation !important;
      -webkit-user-select: none !important;
      user-select: none !important;
      -webkit-text-size-adjust: 100% !important;
    }
  `;
  document.head.appendChild(style);

  // 监听缩放事件（可选，用于调试）
  let lastScale = 1;
  const handleTouchStart = (e: TouchEvent) => {
    if (e.touches.length === 2) {
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const distance = Math.sqrt(Math.pow(touch2.clientX - touch1.clientX, 2) + Math.pow(touch2.clientY - touch1.clientY, 2));
      lastScale = distance;
    }
  };

  const handleTouchMove = (e: TouchEvent) => {
    if (e.touches.length === 2) {
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const distance = Math.sqrt(Math.pow(touch2.clientX - touch1.clientX, 2) + Math.pow(touch2.clientY - touch1.clientY, 2));
      const scale = distance / lastScale;
      if (Math.abs(scale - 1) > 0.1) {
        console.log('检测到缩放手势，缩放比例:', scale);
      }
    }
  };

  document.addEventListener('touchstart', handleTouchStart, { passive: true });
  document.addEventListener('touchmove', handleTouchMove, { passive: true });

  console.log('已设置支持缩放的 viewport 和样式');
};
/**
 * 对外暴露子组件方法
 */
defineExpose({
  init
});
</script>
<style lang="scss" scoped>
.container {
  /* 保持固定宽度 1200px，支持缩放查看 */
  width: 1200px;
  height: 100vh;
  padding: 0;
  margin: 0;

  /* 支持缩放的关键 CSS */
  touch-action: manipulation; /* 允许缩放手势 */
  -webkit-user-select: none; /* 禁用文本选择，避免与缩放冲突 */
  user-select: none;

  /* 确保在小屏幕上可以通过缩放查看完整内容 */
  overflow-x: auto; /* 水平滚动条，以防内容超出屏幕 */
}

.fullscreen-card {
  width: 100%;
  height: 100vh;

  .el-card__body {
    height: 100%;
    overflow: auto;
    padding: 0 20px;

    /* 确保内容在缩放时正确显示 */
    box-sizing: border-box;
  }
}

/* 移除响应式设计，保持固定 1200px 宽度 */

/* 全局样式：确保整个页面支持缩放 */
:global(html, body) {
  touch-action: manipulation !important;
  -webkit-text-size-adjust: 100% !important;
  -webkit-user-select: none !important;
  user-select: none !important;
}

/* 表格在缩放时的优化 */
:deep(.el-table) {
  font-size: 14px;

  .el-table__cell {
    padding: 8px 0;
  }
}

/* 标签页在缩放时的优化 */
:deep(.el-tabs__nav-wrap) {
  overflow-x: auto;
}
</style>
